const moment = require('moment');
const db = require('../config/db');

/**
 * 卖家控制器 - 处理卖家特有功能
 * 包含订单管理等卖家权限操作
 */

/**
 * 获取卖家订单列表（支持分页和筛选）
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.getOrders = async (req, res) => {
  try {
    const sellerId = req.user.user_id;
    const { orderId, productName, status, startDate, endDate, page = 1, pageSize = 10 } = req.query;
    const currentPage = parseInt(page, 10);
    const itemsPerPage = parseInt(pageSize, 10);
    const offset = (currentPage - 1) * itemsPerPage;

    const queryParams = [];
    const countParams = [];
    let query = `
      SELECT o.order_id, o.product_id, p.title AS product_name, o.buyer_id, u.username AS buyer_name, 
             CAST(o.price AS DECIMAL(10,2)) AS total_amount, o.status, o.created_at, o.updated_at
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u ON o.buyer_id = u.user_id
      WHERE o.seller_id = ?
    `;
    let countQuery = `
      SELECT COUNT(*) as total
      FROM orders o
      JOIN products p ON o.product_id = p.product_id
      JOIN users u ON o.buyer_id = u.user_id
      WHERE o.seller_id = ?
    `;

    queryParams.push(sellerId);
    countParams.push(sellerId);

    // 构建查询条件
    if (orderId) {
      query += ' AND o.order_id LIKE ?';
      countQuery += ' AND o.order_id LIKE ?';
      queryParams.push(`%${orderId}%`);
      countParams.push(`%${orderId}%`);
    }

    if (productName) {
      query += ' AND p.title LIKE ?';
      countQuery += ' AND p.title LIKE ?';
      queryParams.push(`%${productName}%`);
      countParams.push(`%${productName}%`);
    }

    if (status !== undefined) {
      query += ' AND o.status = ?';
      countQuery += ' AND o.status = ?';
      queryParams.push(parseInt(status, 10));
      countParams.push(parseInt(status, 10));
    }

    if (startDate) {
      query += ' AND o.created_at >= ?';
      countQuery += ' AND o.created_at >= ?';
      queryParams.push(startDate);
      countParams.push(startDate);
    }

    if (endDate) {
      query += ' AND o.created_at <= ?';
      countQuery += ' AND o.created_at <= ?';
      queryParams.push(endDate);
      countParams.push(endDate);
    }

    // 添加排序逻辑
    query += ' ORDER BY o.created_at DESC';

    // 添加分页参数
    query += ' LIMIT ? OFFSET ?';
    queryParams.push(itemsPerPage, offset);

    // 输出调试信息
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [卖家获取订单列表] SQL: ${query}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [卖家获取订单列表] 参数: ${JSON.stringify(queryParams)}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [卖家获取订单列表] 计数SQL: ${countQuery}`);
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [DEBUG] [卖家获取订单列表] 计数参数: ${JSON.stringify(countParams)}`);

    // 执行查询
    const [orders] = await db.query(query, queryParams);
    const [countResult] = await db.query(countQuery, countParams);

    const totalItems = countResult[0].total;
    const totalPages = Math.ceil(totalItems / itemsPerPage);

    // 记录查询日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [卖家订单查询] 卖家ID: ${sellerId}, 请求参数: ${JSON.stringify(req.query)}, 总数量: ${totalItems}, 当前页: ${currentPage}`);

    res.json({
      success: true,
      orders,
      pagination: {
        currentPage,
        pageSize: itemsPerPage,
        totalItems,
        totalPages
      }
    });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [卖家订单查询失败] ${error.message}`);
    res.status(500).json({ success: false, error: '获取订单列表失败' });
  }
};

/**
 * 更新订单状态
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.updateOrderStatus = async (req, res) => {
  try {
    const sellerId = req.user.user_id;
    const { order_id } = req.params;

    // 检查订单是否存在且属于当前卖家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND seller_id = ?',
      [order_id, sellerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前卖家' });
    }

    const order = orders[0];
    let newStatus;

    // 根据当前状态确定新状态
    switch (order.status) {
      case 0: // 待付款
        newStatus = 1; // 已付款
        break;
      case 1: // 已付款
        newStatus = 2; // 已发货
        break;
      case 3: // 已收货
        newStatus = 4; // 已完成
        break;
      default:
        return res.status(400).json({ success: false, error: '当前订单状态不允许进行此操作' });
    }

    // 更新订单状态
    await db.execute(
      'UPDATE orders SET status = ?, updated_at = ? WHERE order_id = ?',
      [newStatus, moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 如果订单完成，同步更新交易记录状态为成功，并将商品状态更新为已售
    if (newStatus === 4) {
      await db.execute(
        'UPDATE transactions SET status = 1 WHERE order_id = ?',
        [order_id]
      );
      
      // 获取订单对应的商品ID
      const [orderDetails] = await db.execute(
        'SELECT product_id FROM orders WHERE order_id = ?',
        [order_id]
      );
      
      if (orderDetails.length > 0) {
        const productId = orderDetails[0].product_id;
        // 更新商品状态为已售
        await db.execute(
          'UPDATE products SET status = 2 WHERE product_id = ?',
          [productId]
        );
        console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [卖家订单完成] 更新商品状态为已售，商品ID: ${productId}`);
      }
    }

    // 记录更新日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [卖家更新订单状态] 订单ID: ${order_id}, 卖家ID: ${sellerId}, 旧状态: ${order.status}, 新状态: ${newStatus}`);

    res.json({ success: true, message: '订单状态更新成功', newStatus });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [卖家更新订单状态失败] ${error.message}`);
    res.status(500).json({ success: false, error: '更新订单状态失败' });
  }
};

/**
 * 取消订单
 * @param {Object} req - 请求对象
 * @param {Object} res - 响应对象
 */
exports.cancelOrder = async (req, res) => {
  try {
    const sellerId = req.user.user_id;
    const { order_id } = req.params;

    // 检查订单是否存在且属于当前卖家
    const [orders] = await db.execute(
      'SELECT * FROM orders WHERE order_id = ? AND seller_id = ?',
      [order_id, sellerId]
    );

    if (orders.length === 0) {
      return res.status(404).json({ success: false, error: '订单不存在或不属于当前卖家' });
    }

    const order = orders[0];

    // 检查订单状态是否允许取消
    if (![0, 1, 2, 3].includes(order.status)) {
      return res.status(400).json({ success: false, error: '当前订单状态不允许取消' });
    }

    // 更新订单状态为已取消
    await db.execute(
      'UPDATE orders SET status = 5, updated_at = ? WHERE order_id = ?',
      [moment().format('YYYY-MM-DD HH:mm:ss'), order_id]
    );

    // 同步更新交易记录状态为失败
    await db.execute(
      'UPDATE transactions SET status = 2 WHERE order_id = ?',
      [order_id]
    );
    
    // 获取订单对应的商品ID
    const [orderDetails] = await db.execute(
      'SELECT product_id FROM orders WHERE order_id = ?',
      [order_id]
    );
    
    if (orderDetails.length > 0) {
      const productId = orderDetails[0].product_id;
      // 更新商品状态为在售
      await db.execute(
        'UPDATE products SET status = 1 WHERE product_id = ?',
        [productId]
      );
      console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [卖家取消订单] 更新商品状态为在售，商品ID: ${productId}`);
    }

    // 记录取消日志
    console.log(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [INFO] [卖家取消订单] 订单ID: ${order_id}, 卖家ID: ${sellerId}, 原状态: ${order.status}`);

    res.json({ success: true, message: '订单已成功取消' });
  } catch (error) {
    console.error(`[${moment().format('YYYY-MM-DD HH:mm:ss')}] [ERROR] [卖家取消订单失败] ${error.message}`);
    res.status(500).json({ success: false, error: '取消订单失败' });
  }
};